﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint;
using System.Management;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using System.Collections;
using System.IO;
using System.Collections.ObjectModel;
using Microsoft.SharePoint.WebControls;

namespace SharePointHSNC
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            LoaditUp();


        }

        public class ComboboxItem
        {
            public string Text { get; set; }
            public object Value { get; set; }

            public override string ToString()
            {
                return Text;
            }
        }

        private void comboWebApps_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void lblWebApps_Click(object sender, EventArgs e)
        {

        }

        private void btnSelectWebApp_Click(object sender, EventArgs e)
        {
            btnSelectWebApp.Enabled = false;
            comboWebApps.Enabled = false;
            btnReset.Visible = true;

            SPWebApplicationCollection webAppColl = SPWebService.ContentService.WebApplications;

            SPWebApplication selectedWebapp = webAppColl[comboWebApps.SelectedItem.ToString()];

           

            if (selectedWebapp != null)
            {
                foreach (SPSite sitecol in selectedWebapp.Sites)
                {
                    listExistingURL.Items.Add(sitecol.Url);                   
                }
            }

            listExistingURL.Visible = true;
            btnAddNewSiteCol.Visible = true;
            lblExistingSiteCollection.Visible = true;
            
        }

        private void btnAddNewSiteCol_Click(object sender, EventArgs e)
        {
            //Fill Templates and Languages Combo Boxes
            FillLanguages();
            fillContentDBS();

            // Show the Labels
            lblnewSCPrimaryOwner.Visible = true; 
            lblNewSCURL.Visible = true;
            btnCreate.Visible = true;

            //Show the Textboxes
            txtNewSCURL.Visible = true;
            txtNewSCPrimaryOwner.Visible = true;

            //Show the Choices for HSNC Parameters
            chkSCName.Visible = true;
            chkSCDescription.Visible = true;
            chkSCLanguage.Visible = true;
            chkSCTemplate.Visible = true;
            chkSCSecondaryOwner.Visible = true;
            chkContentDB.Visible = true;




      }

        private void btnCreate_Click(object sender, EventArgs e)
        {
            //get the Web Application Selected

            SPWebApplicationCollection webAppColl = SPWebService.ContentService.WebApplications;
            SPWebApplication selectedWebapp = webAppColl[comboWebApps.SelectedItem.ToString()];

            DisableFields();

            //Show Log List
            listLog.Visible = true;
            listLog.Items.Add("--------------------------------------------STARTING LOG ---------------------------------------");
          
            //Get Mandatory Fields
            String SCURL = txtNewSCURL.Text;
            String SCowner = txtNewSCPrimaryOwner.Text;

           


            try
            {

                if (SCURL != "" && SCowner != "")
                {
                     listLog.Items.Add("Starting to Create SiteCollection " + SCURL);
                    //get the GUID of the Web Application
                    ComboboxItem typeItem3 = (ComboboxItem)comboWebApps.SelectedItem;
                    String TheWebAppGuid = typeItem3.Value.ToString();

                    //Check if we create a new Content DB
                    if (chkNewSCContentDB.Checked && chkContentDB.Checked)
                    {
                        try
                        {
                            String SCDB = txtNewSCContentDB.Text;
                            int SCDBWarningCount = int.Parse(txtCDBWarningCount.Text);
                            int SCDBMaxSiteCount = int.Parse(txtCDBMaxSiteCount.Text);
                            if (SCDBWarningCount > SCDBMaxSiteCount)
                            {
                                btnCreate.Visible = false;
                                btnReset.Visible = true;
                                listLog.Items.Add("The Max Site Count must be Bigger then the Warning Count for the Content Databases");
                                listLog.Items.Add("Please Click Restart Button on Top Right and Re-enter Information");
                                return;
                            }


                            if (SCDBWarningCount < SCDBMaxSiteCount && SCDBMaxSiteCount != 0 && SCDBWarningCount != 0 && SCDB != "")
                            {
                                listLog.Items.Add("Creating Content Database " + SCDB);

                                SPContentDatabase copyFromDb = selectedWebapp.ContentDatabases[0];
                                SPContentDatabase contentDb = selectedWebapp.ContentDatabases.Add(copyFromDb.Server, SCDB, copyFromDb.Username, copyFromDb.Password, SCDBWarningCount, SCDBMaxSiteCount, 0);
                                listLog.Items.Add("Content Database " + SCDB + " succesfully created.");
                            }
                        }
                        catch (Exception error)
                        {
                            btnReset.Visible = true;
                            listLog.Items.Add(error.Message);
                            throw;
                        }
                    }


                    //Prepare PowerShell Commmand
                    SPSite site = new SPSite("http://localhost");
                    SPSiteCollection siteCollection = site.WebApplication.Sites;
                    Runspace runspace2 = RunspaceFactory.CreateRunspace();
                    runspace2.Open();
                    RunspaceInvoke runSpaceInvoker = new RunspaceInvoke(runspace2);
                    runSpaceInvoker.Invoke("Set-ExecutionPolicy Unrestricted");
                    runSpaceInvoker.Invoke("Add-PSSnapin 'Microsoft.SharePoint.PowerShell'");
                    Pipeline pipeline = runspace2.CreatePipeline();
                    Command command = new Command("New-SPSite");

                    //Add Mandatory Parameters 
                    command.Parameters.Add("Url", SCURL);
                    command.Parameters.Add("OwnerAlias", SCowner);
                    command.Parameters.Add("HostHeaderWebApplication", TheWebAppGuid);

                    //Check if we Name it  
                    if (chkSCName.Checked && txtSCName.Text != "")
                    {
                        string SiteCollectionName = txtSCName.Text;
                        listLog.Items.Add("Site Collection Name is " + SiteCollectionName);
                        command.Parameters.Add("Name", SiteCollectionName);

                    }

                    //Check if we Description it  
                    if (chkSCDescription.Checked && txtNewSCDescription.Text != "")
                    {
                        string SiteCollectionDescription = txtNewSCDescription.Text;
                        listLog.Items.Add("Site Collection Description  is " + SiteCollectionDescription);
                        command.Parameters.Add("Description", SiteCollectionDescription);
                    }

                    //Check if we give it a language
                    if (chkSCLanguage.Checked)
                    {
                        ComboboxItem typeItem = (ComboboxItem)comboLanguages.SelectedItem;
                        String SCLCID = typeItem.Value.ToString();
                        listLog.Items.Add("Site Collection LCID  is " + SCLCID);
                        command.Parameters.Add("Language", SCLCID);
                    }

                    //Check if we give it a template
                    if (chkSCTemplate.Checked && textBox1.Text != "")
                    {
                        String SCTemplate = textBox1.Text;
                        listLog.Items.Add("Site Collection Template  is " + SCTemplate);
                        command.Parameters.Add("Template", SCTemplate);
                    }

                    if (chkSCSecondaryOwner.Checked && txtNewSCSecondaryOwner.Text != "")
                    {
                        String SC2Ownr = txtNewSCSecondaryOwner.Text;
                        listLog.Items.Add("Site Collection Secondary Owner  is " + SC2Ownr);
                        command.Parameters.Add("SecondaryOwnerAlias", SC2Ownr);
                    }

                    if (chkContentDB.Checked)
                    {
                        if (chkNewSCContentDB.Checked)
                        {
                            String thecontentdb = txtNewSCContentDB.Text;
                            listLog.Items.Add("ContentDBUsed is  " + thecontentdb);
                            command.Parameters.Add("ContentDatabase", thecontentdb);
                        }
                        else
                        {
                            String thecontentdb = comboContentDBs.SelectedText;
                            listLog.Items.Add("ContentDBUsed is  " + thecontentdb);
                            command.Parameters.Add("ContentDatabase", thecontentdb);
                        }


                    }

                    listLog.Items.Add("All Parameters added, starting the Create Command");

                    try
                    {

                        pipeline.Commands.Add(command);
                        pipeline.Invoke();
                        runspace2.Close();
                    }
                    catch
                    {
                        btnReset.Visible = true;
                        listLog.Items.Add("Something Went Wrong, Please check your input");
                    }

                    if (pipeline.Error.Count > 0)
                    {
                        listLog.Items.Add("***ERROR****");
                        listLog.Items.Add(pipeline.Error.Read());
                        listLog.Items.Add("***Please Click the Reset Button at the Top and Restart****");
                        btnCreate.Visible = false;
                        btnReset.Visible = true;
                    }
                    else
                    {
                        listLog.Items.Add("SiteCollection " + SCURL + " succesfully created!");

                        btnCreate.Visible = false;
                        btnReset.Visible = true;
                    }
                   

                    
                }
                else
                {

                    MessageBox.Show("THERE WAS AN ERROR WITH YOUR INPUT, PLEASE CHECK URL AND SITE COLLECTION OWNER");
                    btnReset.Visible = true;
                    btnCreate.Visible = true;
                }

            }
            catch (Exception error)
            {
                btnReset.Visible = true;
                listLog.Items.Add("There was an error with your input");
                listLog.Items.Add(error.Message);
                return;
            }


        }

        private void fillContentDBS()
        {
            SPWebApplicationCollection webAppColl = SPWebService.ContentService.WebApplications;
            SPWebApplication selectedWebapp = webAppColl[comboWebApps.SelectedItem.ToString()];

            foreach (SPContentDatabase CDB in selectedWebapp.ContentDatabases)
            {
                string CDBName = CDB.Name;
                ComboboxItem ContentDB1 = new ComboboxItem();
                ContentDB1.Text = CDBName;
                ContentDB1.Value = CDBName;
                comboContentDBs.Items.Add(ContentDB1);
            }

            comboContentDBs.SelectedIndex = 0;

        }

        private void chkNewSCContentDB_CheckedChanged(object sender, EventArgs e)
        {
            if (chkNewSCContentDB.Checked)
            {
                lblCDBMax.Visible = true;
                lblCDBWarning.Visible = true;
                lblnewContentDBNaame.Visible = true;
                txtCDBMaxSiteCount.Visible = true;
                txtCDBWarningCount.Visible = true;
                txtNewSCContentDB.Visible = true;
                comboContentDBs.Visible = false;
            }
            else
            {
                lblCDBMax.Visible = false;
                lblCDBWarning.Visible = false;
                lblnewContentDBNaame.Visible = false;
                txtCDBMaxSiteCount.Visible = false;
                txtCDBWarningCount.Visible = false;
                txtNewSCContentDB.Visible = false;
                comboContentDBs.Visible = true;
            }

        }

        private void FillLanguages()
        {

            SPLanguageCollection installed = SPRegionalSettings.GlobalInstalledLanguages;

            foreach (SPLanguage language in installed)
            {
                int languageLCID = language.LCID;
                String languageDisplayName = language.DisplayName;

                ComboboxItem languages = new ComboboxItem();
                languages.Text = languageDisplayName;
                languages.Value = languageLCID;

                comboLanguages.Items.Add(languages);
            }

            comboLanguages.SelectedIndex = 0;
        }


        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            if (chkSCName.Checked)
            {
                txtSCName.Visible = true;
            }
            else
            {
                txtSCName.Visible = false;
            }
        }

        private void chkSCDescription_CheckedChanged(object sender, EventArgs e)
        {
            if (chkSCDescription.Checked)
            {
                txtNewSCDescription.Visible = true;
            }
            else
            {
                txtNewSCDescription.Visible = false;
            }

        }

        private void chkSCLanguage_CheckedChanged(object sender, EventArgs e)
        {
            if (chkSCLanguage.Checked)
            {
                comboLanguages.Visible = true;
            }
            else
            {
                comboLanguages.Visible = false;
            }
        }

        private void chkSCTemplate_CheckedChanged(object sender, EventArgs e)
        {
            if (chkSCTemplate.Checked)
            {
                textBox1.Visible = true;
                button1.Visible = true;
                textBox1.Enabled = true;
                button1.Enabled = true;
            }
            else
            {
                textBox1.Visible = false;
                button1.Visible = false;
            }
        }

        private void chkSCSecondaryOwner_CheckedChanged(object sender, EventArgs e)
        {
            if (chkSCSecondaryOwner.Checked)
            {
                txtNewSCSecondaryOwner.Visible = true;
            }
            else
            {
                txtNewSCSecondaryOwner.Visible = false;
            }
        }

        private void chkContentDB_CheckedChanged(object sender, EventArgs e)
        {
            if (chkContentDB.Checked)
            {
                chkNewSCContentDB.Visible = true;
                comboContentDBs.Visible = true;
            }
            else
            {
                txtNewSCContentDB.Visible = false;
                chkNewSCContentDB.Visible = false;
                lblCDBMax.Visible = false;
                lblCDBWarning.Visible = false;
                txtCDBMaxSiteCount.Visible = false;
                txtCDBWarningCount.Visible = false;
                comboContentDBs.Visible = false;
                lblnewContentDBNaame.Visible = false;
                chkNewSCContentDB.Checked = false;

            }
        }

        private void tableLayoutPanel1_Paint(object sender, PaintEventArgs e)
        {

        }

        private void listLog_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void DisableFields()
        {

            txtNewSCURL.Enabled = false;
            txtNewSCPrimaryOwner.Enabled = false;
            txtNewSCContentDB.Enabled = false;
            chkNewSCContentDB.Enabled = false;
            lblCDBMax.Enabled = false;
            lblCDBWarning.Enabled = false;
            txtCDBMaxSiteCount.Enabled = false;
            txtCDBWarningCount.Enabled = false;
            comboContentDBs.Enabled = false;
            lblnewContentDBNaame.Enabled = false;
            chkNewSCContentDB.Enabled = false;
            txtNewSCSecondaryOwner.Enabled = false;
            comboLanguages.Enabled = false;
            txtNewSCDescription.Enabled = false;
            txtSCName.Enabled = false;
            btnReset.Visible = false;
            textBox1.Enabled = false;
            button1.Enabled = false;
        }

        private void btnReset_Click(object sender, EventArgs e)
        {
            ResetStuff();
        }

        private void ResetStuff()
        {

            textBox1.Visible = false;
            button1.Visible = false;
            textBox1.Text = "";
            textBox1.Enabled = false;
            txtCDBMaxSiteCount.Text = "";
            txtCDBWarningCount.Text = "";
            txtNewSCContentDB.Text = "";
            txtNewSCDescription.Text = "";
            txtNewSCPrimaryOwner.Text = "";
            txtNewSCSecondaryOwner.Text = "";
            txtNewSCURL.Text = "";
            txtSCName.Text = "";

            txtNewSCContentDB.Visible = false;
            txtNewSCURL.Visible = false;
            txtNewSCPrimaryOwner.Visible = false;
            txtNewSCContentDB.Visible = false;
            chkNewSCContentDB.Visible = false;
            lblCDBMax.Visible = false;
            lblCDBWarning.Visible = false;
            txtCDBMaxSiteCount.Visible = false;
            txtCDBWarningCount.Visible = false;
            
            lblnewContentDBNaame.Visible = false;
            chkNewSCContentDB.Visible = false;
            txtNewSCSecondaryOwner.Visible = false;
            comboLanguages.Visible = false;
            txtNewSCDescription.Visible = false;
            txtSCName.Visible = false;
            txtNewSCURL.Enabled = true;
            txtNewSCPrimaryOwner.Enabled = true;
            txtNewSCContentDB.Enabled = true;
            chkNewSCContentDB.Enabled = true;
            lblCDBMax.Enabled = true;
            lblCDBWarning.Enabled = true;
            txtCDBMaxSiteCount.Enabled = true;
            txtCDBWarningCount.Enabled = true;
            comboContentDBs.Enabled = true;
            lblnewContentDBNaame.Enabled = true;
            chkNewSCContentDB.Enabled = true;
            txtNewSCSecondaryOwner.Enabled = true;
            comboLanguages.Enabled = true;
            txtNewSCDescription.Enabled = true;
            txtSCName.Enabled = true;

            txtNewSCDescription.Text = "";
            txtSCName.Text = "";


            lblCDBMax.Visible = false;
            lblCDBWarning.Visible = false;
            lblExistingSiteCollection.Visible = false;
            lblnewContentDBNaame.Visible = false;
            lblnewSCPrimaryOwner.Visible = false;
            lblNewSCURL.Visible = false;
          

            chkContentDB.Visible = false;
            chkNewSCContentDB.Visible = false;
            chkSCDescription.Visible = false;
            chkSCLanguage.Visible = false;
            chkSCName.Visible = false;
            chkSCTemplate.Visible = false;
            chkSCSecondaryOwner.Visible = false;
            chkContentDB.Checked = false;
            chkNewSCContentDB.Checked = false;
            chkSCDescription.Checked = false;
            chkSCLanguage.Checked = false;
            chkSCName.Checked = false;
            chkSCTemplate.Checked = false;
            chkSCSecondaryOwner.Checked = false;
            

            comboContentDBs.Items.Clear();
            comboLanguages.Items.Clear();
            comboWebApps.Items.Clear();
      

            listExistingURL.Items.Clear();
            listLog.Items.Clear();

            listExistingURL.Visible = false;
            btnAddNewSiteCol.Visible = false;
            lblExistingSiteCollection.Visible = false;
            comboContentDBs.Visible = false;
            listLog.Visible = false;

            LoaditUp();
        }

        private void LoaditUp()
        {

            SPFarm farm = SPFarm.Local;
            SPWebApplicationCollection webAppColl = SPWebService.ContentService.WebApplications;
            if (webAppColl != null)
            {

                foreach (SPWebApplication spWebApp in webAppColl)
                {

                    string webappname = spWebApp.Name;
                    string webappid = spWebApp.Id.ToString();
                    ComboboxItem item = new ComboboxItem();
                    item.Text = webappname;
                    item.Value = webappid;

                    comboWebApps.Items.Add(item);

                }
            }
            comboWebApps.SelectedIndex = 0;
            comboWebApps.Enabled = true;
            btnSelectWebApp.Enabled = true;
            btnReset.Visible = false;
            btnCreate.Visible = false;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Templates frm = new Templates();
            frm.Show();
        } 



    }
}
